<script setup lang="tsx">
import { NDivider } from 'naive-ui';
import { fetchBatchDeleteGameLeaderboard, fetchGetGameLeaderboardList } from '@/service/api/games/game-leaderboard';
import { useAppStore } from '@/store/modules/app';
import { useAuth } from '@/hooks/business/auth';
import { useDownload } from '@/hooks/business/download';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { $t } from '@/locales';
import ButtonIcon from '@/components/custom/button-icon.vue';
import DictTag from '@/components/custom/dict-tag.vue';
import GameLeaderboardOperateDrawer from './modules/game-leaderboard-operate-drawer.vue';
import GameLeaderboardSearch from './modules/game-leaderboard-search.vue';

defineOptions({
  name: 'GameLeaderboardList'
});

const appStore = useAppStore();
const { download } = useDownload();
const { hasAuth } = useAuth();

const {
  columns,
  columnChecks,
  data,
  getData,
  getDataByPage,
  loading,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useTable({
  apiFn: fetchGetGameLeaderboardList,
  apiParams: {
    pageNum: 1,
    pageSize: 10,
    // if you want to use the searchParams in Form, you need to define the following properties, and the value is null
    // the value can not be undefined, otherwise the property in Form will not be reactive
    userId: null,
    gameId: null,
    gameCode: null,
    bestScore: null,
    totalScore: null,
    playCount: null,
    totalTime: null,
    avgScore: null,
    rankType: null,
    rankPeriod: null,
    lastPlayTime: null,
    params: {}
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    {
      key: 'index',
      title: $t('common.index'),
      align: 'center',
      width: 64
    },
    {
      key: 'rankId',
      title: '排行ID',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'userId',
      title: '用户ID',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'gameId',
      title: '游戏ID',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'gameCode',
      title: '游戏编码',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'bestScore',
      title: '最高分数',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'totalScore',
      title: '累计分数',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'playCount',
      title: '游戏次数',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'totalTime',
      title: '累计时长（秒）',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'avgScore',
      title: '平均分数',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'rankType',
      title: '排行类型',
      align: 'center',
      minWidth: 120,
      render: row => {
        return <DictTag dictCode="rank_type" value={row.rankType} />;
      }
    },
    {
      key: 'rankPeriod',
      title: '排行周期（格式：2024-01、2024-W01、2024-01-01）',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'lastPlayTime',
      title: '最后游戏时间',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      width: 130,
      render: row => {
        const divider = () => {
          if (!hasAuth('games:gameLeaderboard:edit') || !hasAuth('games:gameLeaderboard:remove')) {
            return null;
          }
          return <NDivider vertical />;
        };

        const editBtn = () => {
          if (!hasAuth('games:gameLeaderboard:edit')) {
            return null;
          }
          return (
            <ButtonIcon
              text
              type="primary"
              icon="material-symbols:drive-file-rename-outline-outline"
              tooltipContent={$t('common.edit')}
              onClick={() => edit(row.rankId!)}
            />
          );
        };

        const deleteBtn = () => {
          if (!hasAuth('games:gameLeaderboard:remove')) {
            return null;
          }
          return (
            <ButtonIcon
              text
              type="error"
              icon="material-symbols:delete-outline"
              tooltipContent={$t('common.delete')}
              popconfirmContent={$t('common.confirmDelete')}
              onPositiveClick={() => handleDelete(row.rankId!)}
            />
          );
        };

        return (
          <div class="flex-center gap-8px">
            {editBtn()}
            {divider()}
            {deleteBtn()}
          </div>
        );
      }
    }
  ]
});

const { drawerVisible, operateType, editingData, handleAdd, handleEdit, checkedRowKeys, onBatchDeleted, onDeleted } =
  useTableOperate(data, getData);

async function handleBatchDelete() {
  // request
  const { error } = await fetchBatchDeleteGameLeaderboard(checkedRowKeys.value);
  if (error) return;
  onBatchDeleted();
}

async function handleDelete(rankId: CommonType.IdType) {
  // request
  const { error } = await fetchBatchDeleteGameLeaderboard([rankId]);
  if (error) return;
  onDeleted();
}

function edit(rankId: CommonType.IdType) {
  handleEdit('rankId', rankId);
}

function handleExport() {
  download('/games/gameLeaderboard/export', searchParams, `游戏排行榜_${new Date().getTime()}.xlsx`);
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <GameLeaderboardSearch v-model:model="searchParams" @reset="resetSearchParams" @search="getDataByPage" />
    <NCard title="游戏排行榜列表" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          :show-add="hasAuth('games:gameLeaderboard:add')"
          :show-delete="hasAuth('games:gameLeaderboard:remove')"
          :show-export="hasAuth('games:gameLeaderboard:export')"
          @add="handleAdd"
          @delete="handleBatchDelete"
          @export="handleExport"
          @refresh="getData"
        />
      </template>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="962"
        :loading="loading"
        remote
        :row-key="row => row.rankId"
        :pagination="mobilePagination"
        class="sm:h-full"
      />
      <GameLeaderboardOperateDrawer
        v-model:visible="drawerVisible"
        :operate-type="operateType"
        :row-data="editingData"
        @submitted="getDataByPage"
      />
    </NCard>
  </div>
</template>

<style scoped></style>
